package com.hmall.order.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmall.common.client.ItemClient;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.service.IOrderService;
import com.hmall.order.service.OrderDetailService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
public class OrderTask {

    @Autowired
    IOrderService orderService;

    @Autowired
    ItemClient itemClient;

    @Autowired
    OrderDetailService detailsService;

    @GlobalTransactional // 微服务 全局事务
    @Scheduled(cron = "0 * * * * ?") // 一分钟执行一次
    public void cancelOrder(){
        System.out.println("开始执行任务....");
        // 每分钟运行一次定时任务
        // 查找订单表中未支付记录
        // 判断创建订单时间是否已经超过30分钟

        // 获取当前时间往前推30分钟的时间
        Date time = new Date(System.currentTimeMillis() - 30 * 60 * 1000);
        LambdaQueryWrapper<Order> query = new LambdaQueryWrapper<>();
        query.eq(Order::getStatus, 1);
        query.le(Order::getCreateTime, time);
        List<Order> list = orderService.list(query);
        for (Order order : list) {
            // 如果已经超时, 将其  status 修改为 5, 取消订单, 恢复扣减的库存
            order.setStatus(5);
            orderService.updateById(order);
            // 查询订单明细
            LambdaQueryWrapper<OrderDetail> queryDetail = new LambdaQueryWrapper<>();
            queryDetail.eq(OrderDetail::getOrderId, order.getId());
            List<OrderDetail> orderDetails = detailsService.list(queryDetail);
            for (OrderDetail detail : orderDetails) {
                itemClient.reduceStock(detail.getItemId(), -detail.getNum());
            }
        }
    }

}
